package com.wing.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

public class DingDingUtils {
    private static final String APP_KEY = "ding82iytsnrfsu4bb7p";
    private static final String APP_SECRET = "sE3mhPsMaTr-MgmR6vRpKEZmRyBR9YpJeUnu-4kV1MLafAK7U0sgW07eBancMwSF";
    private static final String GET_ACCESS_TOKEN_URL = "https://oapi.dingtalk.com/gettoken?appkey=" + APP_KEY + "&appsecret=" + APP_SECRET;

    public static String getAccessToken() throws Exception {
        URL url = new URL(GET_ACCESS_TOKEN_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            JSONObject jsonObject = new JSONObject(response.toString());
            return jsonObject.getString("access_token");
        } else {
            throw new RuntimeException("Failed : HTTP error code : " + responseCode);
        }
    }

    /**
     * 获取token 拉取信息
     * @param APP_KEY
     * @param APP_SECRET
     * @return
     * @throws Exception
     */
    public static String getAccessTokenByKeySecret(String APP_KEY,String APP_SECRET) throws Exception {
        String GET_ACCESS_TOKEN_URL = "https://oapi.dingtalk.com/gettoken?appkey=" + APP_KEY + "&appsecret=" + APP_SECRET;
        URL url = new URL(GET_ACCESS_TOKEN_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            JSONObject jsonObject = new JSONObject(response.toString());
            return jsonObject.getString("access_token");
        } else {
            throw new RuntimeException("Failed : HTTP error code : " + responseCode);
        }
    }



    private static final String DEPARTMENT_LIST_NEW_URL = "https://oapi.dingtalk.com/topapi/v2/department/listsub";

    /**
     * 获取所有部门信息  根据对应部门id  部门id没有则默认 根订单的所有部门信息
     * @throws Exception
     */
    public static String getDepartmentNewList(String accessToken,String deptId) throws Exception {
        try {
            //String accessToken = DingDingUtils.getAccessToken();

            URL url = new URL(DEPARTMENT_LIST_NEW_URL + "?access_token=" + accessToken);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);


            HashMap josnMap=new HashMap();
            josnMap.put("dept_id",deptId);
            josnMap.put("language","zh_CN");
          /*  String jsonInputString = "{\"dept_id\":986027728,\"language\":\"zh_CN\"}";*/
            String jsonInputString = JSON.toJSONString(josnMap);
            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                // print result
                System.out.println(response.toString());
                return response.toString();
            } else {
                System.out.println("POST request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static final String DEPARTMENT_USER_LIST_URL = "https://oapi.dingtalk.com/topapi/user/listsimple";


    /**
     * 获取对应部门下面的用户  根据部门id和分页参数
     * @throws Exception
     */
    public static String getDepartUserList(String accessToken,Long deptId,int page,int size) throws Exception {
        try {
            //String accessToken = DingDingUtils.getAccessToken();

            URL url = new URL(DEPARTMENT_USER_LIST_URL + "?access_token=" + accessToken);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

         /*   String jsonInputString = "{\"dept_id\":986027728,\"cursor\":\"0\",\"size\":\"100\"}";*/

            HashMap josnMap=new HashMap();
            josnMap.put("dept_id",deptId);
            josnMap.put("cursor",page);
            josnMap.put("size",size);

            String jsonInputString = JSON.toJSONString(josnMap);

            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                // print result
                System.out.println(response.toString());
                return response.toString();
            } else {
                System.out.println("POST request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
         return null;
    }

    private static final String GET_USER_DETAIL_URL = "https://oapi.dingtalk.com/topapi/v2/user/get";

    /**
     *  查看用户详情信息
     * @throws Exception
     */
    public static void getUserDetailInfo(String accessToken) throws Exception {
        try {
/*            String accessToken = DingDingUtils.getAccessToken();*/

            URL url = new URL(GET_USER_DETAIL_URL + "?access_token=" + accessToken);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            String jsonInputString = "{\"language\":\"zh_CN\",\"userid\":\"0902243055755190\"}";

            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                // print result
                System.out.println(response.toString());
            } else {
                System.out.println("POST request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    private static final String GET_DEPT_USER_URL = "https://oapi.dingtalk.com/topapi/v2/user/list";

    /**
     *  查看部门 用户详情信息 列表（部门下面所有用户的详情信息） 不包含子部门
     * @throws Exception
     */
    public static String getDeptUserDetailListInfo(String accessToken,Long deptId,int page,int size) throws Exception {
        try {
          /*  String accessToken = DingDingUtils.getAccessToken();*/

            URL url = new URL(GET_DEPT_USER_URL + "?access_token=" + accessToken);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            //String jsonInputString = "{\"cursor\":\"0\",\"contain_access_limit\":\"false\",\"size\":\"10\",\"order_field\":\"modify_desc\",\"language\":\"zh_CN\",\"dept_id\":\"1\"}";

            HashMap josnMap=new HashMap();
            josnMap.put("dept_id",deptId);
            josnMap.put("cursor",page);
            josnMap.put("size",size);
            josnMap.put("language","zh_CN");
            josnMap.put("order_field","modify_desc");
            josnMap.put("contain_access_limit","false");

            String jsonInputString = JSON.toJSONString(josnMap);

            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                // print result
                System.out.println(response.toString());
                return response.toString();
            } else {
                System.out.println("POST request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    private static final String GET_COMPANY_USER_SUM_COUNT_URL = "https://oapi.dingtalk.com/topapi/user/count";

    /**
     *  查看公司用户总数
     * @throws Exception
     */
    public static void getCompanyUserSumCount(String accessToken) throws Exception {
        try {
          /*  String accessToken = DingDingUtils.getAccessToken();*/

            URL url = new URL(GET_COMPANY_USER_SUM_COUNT_URL + "?access_token=" + accessToken);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            String jsonInputString = "{\"only_active\":\"false\"}";

            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                //{"errcode":0,"errmsg":"ok","result":{"count":2},"request_id":"16l1hc1bar0y4"}
               // print result
                System.out.println(response.toString());
            } else {
                System.out.println("POST request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    private static final String GET_DEPT_DETAIL_URL = "https://oapi.dingtalk.com/topapi/v2/department/get";

    /**
     *  获取部门详情信息
     * @throws Exception
     */
    public static void getDeptDetail(String accessToken) throws Exception {
        try {
            /*String accessToken = DingDingUtils.getAccessToken();*/

            URL url = new URL(GET_DEPT_DETAIL_URL + "?access_token=" + accessToken);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            String jsonInputString = "{\"dept_id\":\"1\"}";

            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                //{"errcode":0,"errmsg":"ok","result":{"count":2},"request_id":"16l1hc1bar0y4"}
                // print result
                System.out.println(response.toString());
            } else {
                System.out.println("POST request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static final String GET_DEPT_IDS_URL = "https://oapi.dingtalk.com/topapi/v2/department/listsubid";

    /**
     *  获取部门下 部门id集合信息
     * @throws Exception
     */
    public static void getDeptIds(String accessToken) throws Exception {
        try {
         /*   String accessToken = DingDingUtils.getAccessToken();*/

            URL url = new URL(GET_DEPT_IDS_URL + "?access_token=" + accessToken);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            String jsonInputString = "{\"dept_id\":\"986373096\"}";

            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                //{"errcode":0,"errmsg":"ok","result":{"count":2},"request_id":"16l1hc1bar0y4"}
                // print result
                System.out.println(response.toString());
            } else {
                System.out.println("POST request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }







    private static final String CREATE_DEPT_URL = "https://oapi.dingtalk.com/topapi/v2/department/create";

    /**
     *  创建部门
     * @throws Exception
     */
    public static void createDeptInfo(String accessToken) throws Exception {
        try {
          /*  String accessToken = DingDingUtils.getAccessToken();*/

            URL url = new URL(CREATE_DEPT_URL + "?access_token=" + accessToken);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            String jsonInputString = "{\"name\":\"架构组\",\"parent_id\":986373096}";

            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                //{"errcode":0,"errmsg":"ok","result":{"count":2},"request_id":"16l1hc1bar0y4"}
                // print result
                System.out.println(response.toString());
            } else {
                System.out.println("POST request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static final String UPDATE_DEPT_URL = "https://oapi.dingtalk.com/topapi/v2/department/update";

    /**
     *  修改部门
     * @throws Exception
     */
    public static void updateDeptInfo(String accessToken) throws Exception {
        try {
/*            String accessToken = DingDingUtils.getAccessToken();*/

            URL url = new URL(UPDATE_DEPT_URL + "?access_token=" + accessToken);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            String jsonInputString = "{\"name\":\"架构组\",\"dept_id\":986082865}";

            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                //{"errcode":0,"errmsg":"ok","result":{"count":2},"request_id":"16l1hc1bar0y4"}
                // print result
                System.out.println(response.toString());
            } else {
                System.out.println("POST request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static final String DELETE_DEPT_URL = "https://oapi.dingtalk.com/topapi/v2/department/delete";

    /**
     *  删除部门
     * @throws Exception
     */
    public static void deleteDeptInfo(String accessToken) throws Exception {
        try {
/*            String accessToken = DingDingUtils.getAccessToken();*/

            URL url = new URL(DELETE_DEPT_URL + "?access_token=" + accessToken);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            String jsonInputString = "{\"dept_id\":985720942}";

            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                //{"errcode":0,"errmsg":"ok","result":{"count":2},"request_id":"16l1hc1bar0y4"}
                // print result
                System.out.println(response.toString());
            } else {
                System.out.println("POST request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static final String CREATE_USER_URL = "https://oapi.dingtalk.com/topapi/v2/user/create";

    /**
     *  创建用户
     * @throws Exception
     */
    public static void createUserInfo(String accessToken) throws Exception {
        try {
/*            String accessToken = DingDingUtils.getAccessToken();*/

            URL url = new URL(CREATE_USER_URL + "?access_token=" + accessToken);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            String jsonInputString = "{\"name\":\"zhangshan\",\"mobile\":\"15580036599\",\"dept_id_list\":\"1\"}";

            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                //{"errcode":0,"errmsg":"ok","result":{"count":2},"request_id":"16l1hc1bar0y4"}
                // print result
                System.out.println(response.toString());
            } else {
                System.out.println("POST request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    private static final String UPDATE_USER_URL = "https://oapi.dingtalk.com/topapi/v2/user/update";

    /**
     *  修改用户
     * @throws Exception
     */
    public static void updateUserInfo(String accessToken) throws Exception {
        try {
/*            String accessToken = DingDingUtils.getAccessToken();*/

            URL url = new URL(UPDATE_USER_URL + "?access_token=" + accessToken);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            String jsonInputString = "{\"name\":\"hezhou1\",\"mobile\":\"17363771838\",\"userid\":\"2209150756-1220521967\"}";

            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                //{"errcode":0,"errmsg":"ok","result":{"count":2},"request_id":"16l1hc1bar0y4"}
                // print result
                System.out.println(response.toString());
            } else {
                System.out.println("POST request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static final String ATTENDANCE_URL = "https://oapi.dingtalk.com/topapi/attendance/group/minimalism/list";

    /**
     *  批量获取考勤组摘要
     * @throws Exception
     */
    public static void getAttendanceZhaiYao(String accessToken) throws Exception {
        try {
         /*   String accessToken = DingDingUtils.getAccessToken();*/

            URL url = new URL(ATTENDANCE_URL + "?access_token=" + accessToken);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            String jsonInputString = "{\"op_user_id\":\"manager3745\"}";

            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                //{"errcode":0,"errmsg":"ok","result":{"count":2},"request_id":"16l1hc1bar0y4"}
                // print result
                System.out.println(response.toString());
            } else {
                System.out.println("POST request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    private static final String SIMPLEGROUPS_URL = "https://oapi.dingtalk.com/topapi/attendance/getsimplegroups";

    /**
     *  批量获取考勤组详情
     * @throws Exception
     */
    public static String getsimplegroupsDetail(String accessToken) throws Exception {
        try {
/*            String accessToken = DingDingUtils.getAccessToken();*/

            URL url = new URL(SIMPLEGROUPS_URL + "?access_token=" + accessToken);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            String jsonInputString = "";

            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                //{"errcode":0,"errmsg":"ok","result":{"count":2},"request_id":"16l1hc1bar0y4"}
                // print result
                System.out.println(response.toString());
                return response.toString();
            } else {
                System.out.println("POST request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    private static final String GET_USER_GROUP_URL = "https://oapi.dingtalk.com/topapi/attendance/getusergroup";

    /**
     *  获取用户考勤组 根据用户id
     * @throws Exception
     */
    public static void getUserGroupDetail(String accessToken) throws Exception {
        try {
/*            String accessToken = DingDingUtils.getAccessToken();*/

            URL url = new URL(GET_USER_GROUP_URL + "?access_token=" + accessToken);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            String jsonInputString = "{\"userid\":\"0902243055755190\"}";

            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                //{"errcode":0,"errmsg":"ok","result":{"count":2},"request_id":"16l1hc1bar0y4"}
                // print result
                System.out.println(response.toString());
            } else {
                System.out.println("POST request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    private static final String ATTENDANCE_LIST_DAY_URL = "https://oapi.dingtalk.com/topapi/attendance/schedule/listbyday";

    /**
     * 查询成员排班信息 根据用户id
     * @throws Exception
     */
    public static void getUserAttendanceByDay(String accessToken) throws Exception {
        try {
/*            String accessToken = DingDingUtils.getAccessToken();*/

            URL url = new URL(ATTENDANCE_LIST_DAY_URL + "?access_token=" + accessToken);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);


            String jsonInputString = "{\"op_user_id\":\"manager3745\",\"user_id\":\"0902243055755190\",\"date_time\":\"1738857600000\"}";
            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                //{"errcode":0,"errmsg":"ok","result":{"count":2},"request_id":"16l1hc1bar0y4"}
                // print result
                System.out.println(response.toString());
            } else {
                System.out.println("POST request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static final String GET_USER_PAI_BAN_INFO_URL = "https://oapi.dingtalk.com/topapi/attendance/schedule/listbyusers";

    /**
     *  批量查询人员排班信息  通过管理负责人  查看对应用户的排班信息
     * @throws Exception
     */
    public static String getUserPaiBanInfo(String accessToken,Long fromDateTime,Long toDateTime,String opUserId,String userIds) throws Exception {
        try {
/*            String accessToken = DingDingUtils.getAccessToken();*/

            URL url = new URL(GET_USER_PAI_BAN_INFO_URL + "?access_token=" + accessToken);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            //String jsonInputString = "{\"from_date_time\":1738771368000,\"op_user_id\":\"manager3745\",\"userids\":\"0902243055755190,manager3745\",\"to_date_time\":1738944168000}";

            HashMap josnMap=new HashMap();
            josnMap.put("from_date_time",fromDateTime);
            josnMap.put("op_user_id",opUserId);
            josnMap.put("userids",userIds);
            josnMap.put("to_date_time",toDateTime);

            String jsonInputString = JSON.toJSONString(josnMap);

            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                //{"errcode":0,"errmsg":"ok","result":{"count":2},"request_id":"16l1hc1bar0y4"}
                // print result
                System.out.println(response.toString());
                return response.toString();
            } else {
                System.out.println("POST request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }




    private static final String GET_USER_MANAGER_INFO_URL = "https://oapi.dingtalk.com/topapi/user/listadmin";

    /**
     *  获取钉钉管理人员信息
     * @throws Exception
     */
    public static String getUserManagerInfo(String accessToken) throws Exception {
        try {
            /*            String accessToken = DingDingUtils.getAccessToken();*/

            URL url = new URL(GET_USER_MANAGER_INFO_URL + "?access_token=" + accessToken);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

          /*  String jsonInputString = "{\"from_date_time\":1738771368000,\"op_user_id\":\"manager3745\",\"userids\":\"0902243055755190\",\"to_date_time\":1738944168000}";

            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }*/

            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                //{"errcode":0,"errmsg":"ok","result":{"count":2},"request_id":"16l1hc1bar0y4"}
                // print result
                System.out.println(response.toString());
                return response.toString();
            } else {
                System.out.println("POST request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }




    private static final String GET_USER_HISTORY_BAN_CI_INFO_URL = "https://oapi.dingtalk.com/topapi/attendance/shift/history/query";

    /**
     *  查询历史班次  可以获取到相关班次名称
     * @throws Exception
     */
    public static String getUserHistoryBanCiInfo(String accessToken,Long shiftId,String version,String opUserId) throws Exception {
        try {
            /*            String accessToken = DingDingUtils.getAccessToken();*/
            URL url = new URL(GET_USER_HISTORY_BAN_CI_INFO_URL + "?access_token=" + accessToken);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            HashMap josnMap=new HashMap();

            josnMap.put("shift_id",shiftId);
            josnMap.put("version",version);
            josnMap.put("op_user_id",opUserId);
            String jsonInputString = JSON.toJSONString(josnMap);

      /*      josnMap.put("shift_id","1324688457");
            josnMap.put("version","1260016868");
            josnMap.put("op_user_id","manager3745");*/
           //String jsonInputString = "{\"from_date_time\":1738771368000,\"op_user_id\":\"manager3745\",\"userids\":\"0902243055755190\",\"to_date_time\":1738944168000}";

            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                //{"errcode":0,"errmsg":"ok","result":{"count":2},"request_id":"16l1hc1bar0y4"}
                // print result {"errcode":0,"errmsg":"ok","result":{"corp_id":"ding269a8fdbe113c0ae","id":1324688457,"name":"生产部晚班","sections":[{"id":988183037,"punches":[{"across":0,"check_time":"1970-01-01 13:00:00","check_type":"OnDuty","free_check":false,"id":1072938245,"permit_minutes":0},{"across":0,"check_time":"1970-01-01 22:00:00","check_type":"OffDuty","free_check":false,"id":1072938246}],"rests":[{"across":0,"check_time":"1970-01-01 14:00:00","check_type":"OnDuty","id":1072938247},{"across":0,"check_time":"1970-01-01 15:00:00","check_type":"OffDuty","id":1072938248}]}],"shift_setting":{"attend_days":"1.0","corp_id":"ding269a8fdbe113c0ae","gmt_create":"2025-02-06 18:07:47","gmt_modified":"2025-02-06 18:07:47","id":1260016868,"is_deleted":"N","shift_id":1324688457,"work_time_minutes":480}},"success":true,"request_id":"16m219peshnkb"}
                System.out.println(response.toString());
                return response.toString();
            } else {
                System.out.println("POST request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private static final String GET_ATTENDANCE_QUERY_INFO_URL = "https://oapi.dingtalk.com/topapi/attendance/group/query";

    /**
     *  获取考勤组详情信息
     * @throws Exception
     */
    public static String getAttendanceDetailInfo(String accessToken,Long groupId,String opUserId) throws Exception {
        try {
            /*            String accessToken = DingDingUtils.getAccessToken();*/
            URL url = new URL(GET_ATTENDANCE_QUERY_INFO_URL + "?access_token=" + accessToken);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            HashMap josnMap=new HashMap();

            josnMap.put("group_id",groupId);
            josnMap.put("op_user_id",opUserId);
            String jsonInputString = JSON.toJSONString(josnMap);

            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                //{"errcode":0,"errmsg":"ok","result":{"count":2},"request_id":"16l1hc1bar0y4"}
                // print result {"errcode":0,"errmsg":"ok","result":{"corp_id":"ding269a8fdbe113c0ae","id":1324688457,"name":"生产部晚班","sections":[{"id":988183037,"punches":[{"across":0,"check_time":"1970-01-01 13:00:00","check_type":"OnDuty","free_check":false,"id":1072938245,"permit_minutes":0},{"across":0,"check_time":"1970-01-01 22:00:00","check_type":"OffDuty","free_check":false,"id":1072938246}],"rests":[{"across":0,"check_time":"1970-01-01 14:00:00","check_type":"OnDuty","id":1072938247},{"across":0,"check_time":"1970-01-01 15:00:00","check_type":"OffDuty","id":1072938248}]}],"shift_setting":{"attend_days":"1.0","corp_id":"ding269a8fdbe113c0ae","gmt_create":"2025-02-06 18:07:47","gmt_modified":"2025-02-06 18:07:47","id":1260016868,"is_deleted":"N","shift_id":1324688457,"work_time_minutes":480}},"success":true,"request_id":"16m219peshnkb"}
                System.out.println(response.toString());
                return response.toString();
            } else {
                System.out.println("POST request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }




    private static final String GET_ATTENDANCE_SHIFT_INFO_URL = "https://oapi.dingtalk.com/topapi/attendance/shift/list";

    /**
     *  获取班次信息
     * @throws Exception
     */
    public static String getAttendanceShiftInfo(String accessToken,Long cursor,String opUserId) throws Exception {
        try {
            /*            String accessToken = DingDingUtils.getAccessToken();*/
            URL url = new URL(GET_ATTENDANCE_SHIFT_INFO_URL + "?access_token=" + accessToken);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            HashMap josnMap=new HashMap();

            josnMap.put("cursor",cursor);
            josnMap.put("op_user_id",opUserId);
            String jsonInputString = JSON.toJSONString(josnMap);

            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                //{"errcode":0,"errmsg":"ok","result":{"count":2},"request_id":"16l1hc1bar0y4"}
                // print result {"errcode":0,"errmsg":"ok","result":{"corp_id":"ding269a8fdbe113c0ae","id":1324688457,"name":"生产部晚班","sections":[{"id":988183037,"punches":[{"across":0,"check_time":"1970-01-01 13:00:00","check_type":"OnDuty","free_check":false,"id":1072938245,"permit_minutes":0},{"across":0,"check_time":"1970-01-01 22:00:00","check_type":"OffDuty","free_check":false,"id":1072938246}],"rests":[{"across":0,"check_time":"1970-01-01 14:00:00","check_type":"OnDuty","id":1072938247},{"across":0,"check_time":"1970-01-01 15:00:00","check_type":"OffDuty","id":1072938248}]}],"shift_setting":{"attend_days":"1.0","corp_id":"ding269a8fdbe113c0ae","gmt_create":"2025-02-06 18:07:47","gmt_modified":"2025-02-06 18:07:47","id":1260016868,"is_deleted":"N","shift_id":1324688457,"work_time_minutes":480}},"success":true,"request_id":"16m219peshnkb"}
                System.out.println(response.toString());
                return response.toString();
            } else {
                System.out.println("POST request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }





    private static final String GET_ATTENDANCE_SHIFT_DETAIL_INFO_URL = "https://oapi.dingtalk.com/topapi/attendance/shift/query";

    /**
     *  获取考勤组详情信息
     * @throws Exception
     */
    public static String getAttendanceShiftDetailInfo(String accessToken,String shiftId,String opUserId) throws Exception {
        try {
            /*            String accessToken = DingDingUtils.getAccessToken();*/
            URL url = new URL(GET_ATTENDANCE_SHIFT_DETAIL_INFO_URL + "?access_token=" + accessToken);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);

            HashMap josnMap=new HashMap();

            josnMap.put("shift_id",shiftId);
            josnMap.put("op_user_id",opUserId);
            String jsonInputString = JSON.toJSONString(josnMap);

            try(OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                //{"errcode":0,"errmsg":"ok","result":{"count":2},"request_id":"16l1hc1bar0y4"}
                // print result {"errcode":0,"errmsg":"ok","result":{"corp_id":"ding269a8fdbe113c0ae","id":1324688457,"name":"生产部晚班","sections":[{"id":988183037,"punches":[{"across":0,"check_time":"1970-01-01 13:00:00","check_type":"OnDuty","free_check":false,"id":1072938245,"permit_minutes":0},{"across":0,"check_time":"1970-01-01 22:00:00","check_type":"OffDuty","free_check":false,"id":1072938246}],"rests":[{"across":0,"check_time":"1970-01-01 14:00:00","check_type":"OnDuty","id":1072938247},{"across":0,"check_time":"1970-01-01 15:00:00","check_type":"OffDuty","id":1072938248}]}],"shift_setting":{"attend_days":"1.0","corp_id":"ding269a8fdbe113c0ae","gmt_create":"2025-02-06 18:07:47","gmt_modified":"2025-02-06 18:07:47","id":1260016868,"is_deleted":"N","shift_id":1324688457,"work_time_minutes":480}},"success":true,"request_id":"16m219peshnkb"}
                System.out.println(response.toString());
                return response.toString();
            } else {
                System.out.println("POST request failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }




    /**
     * 获取钉钉后台管理人员信息-选择其中一个
     * @param accessToken
     * @return
     * @throws Exception
     */
    public static String getUserManagerInfoOne(String accessToken) throws Exception {
        String userManagerInfo =getUserManagerInfo(accessToken);
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSON.parseObject(userManagerInfo);
        JSONArray resultArray = jsonObject.getJSONArray("result");

        // 初始化一个变量来保存找到的userid
        String targetUserId = null;

        // 遍历数组寻找第一个 sys_level 为 1 的对象
        for (int i = 0; i < resultArray.size(); i++) {
            com.alibaba.fastjson.JSONObject item = resultArray.getJSONObject(i);
            if (item.getIntValue("sys_level") == 1) {
                targetUserId = item.getString("userid");
                break; // 找到后退出循环
            }
        }

        // 在循环外处理找到的userid
        if (targetUserId != null) {
            System.out.println("Found userid: " + targetUserId);
        } else {
            System.out.println("No user with sys_level 1 found.");
        }
        return targetUserId;

    }


    public static void main(String[] args) throws Exception {
          //String jsonInputString = "{\"from_date_time\":1738771368000,\"op_user_id\":\"manager3745\",\"userids\":\"0902243055755190,manager3745\",\"to_date_time\":1738944168000}";
          //getUserPaiBanInfo(DingDingUtils.getAccessToken(),1740585600000L,1740758400000L,"manager3745","0902243055755190,manager3745,2209150756-1220521967");
          // getUserHistoryBanCiInfo(DingDingUtils.getAccessToken());
        //getAttendanceDetailInfo(DingDingUtils.getAccessToken(),1308017030L,"manager3745");
        //getDepartmentNewList(DingDingUtils.getAccessToken(),"");

        //getDeptDetail(DingDingUtils.getAccessToken());

        //getAttendanceShiftInfo(DingDingUtils.getAccessToken(),null,getUserManagerInfoOne(DingDingUtils.getAccessToken()));


        getAttendanceShiftDetailInfo(DingDingUtils.getAccessToken(),"1324688457",getUserManagerInfoOne(DingDingUtils.getAccessToken()));


    }






}
